package com.gym.myshop.web.filter;

import com.gym.myshop.common.Const;
import com.gym.myshop.entity.User;
import com.gym.myshop.services.UserServices;
import com.gym.myshop.services.impl.UserServicesImpl;
import com.gym.myshop.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ming
 * 2021/11/5
 * description:登录处理
 */
@WebFilter(filterName = "Filter02_AutoLogin",value = "/login.jsp")
public class Filter02_AutoLogin implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
            ServletException {
        HttpServletResponse response= (HttpServletResponse) resp;
        HttpServletRequest request= (HttpServletRequest) req;
        //自动登录处理判断
        Cookie[] cookies = request.getCookies();
        if (cookies!=null) {
            for (Cookie cookie : cookies) {
                //遍历查找有没有自动登录的cookie数据存在
                if (cookie.getName().equals(Const.UserConst.AUTO_LOGIN)) {
                    //找到数据
                    String value = cookie.getValue();
                    //解码
                    String decode = Base64Utils.decode(value);
                    //分解用户名和密码   username+":"+password
                    String username = decode.substring(0,decode.indexOf(":"));
                    String password = decode.substring(decode.indexOf(":")+1);
                    //找业务层做登录验证
                    UserServices us = new UserServicesImpl();
                    User login = us.login(username, password);
                    if (login!=null) {
                        //登录成功 跳转到首页
                        request.getSession().setAttribute(Const.UserConst.IS_LOGIN,login);
                        response.sendRedirect(request.getContextPath()+"/index.jsp");
                        //结束离开方法,不需要继续执行
                        return;
                    }
                }
            }
        }
        //放行 自动登录不上
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {

    }
}
